import { useRecoilValue, useRecoilState, useSetRecoilState } from 'recoil';
import { todoListState, filterState, filteredTodoListState } from './recoil';
import { useRef } from 'react';
function RecoilApp() {
    const textRef = useRef();
    //useRecoilState返回一个数组，第1个元素是状态的里值，第2个元素修改状态的方法
    //const [todoList,setTodoList] = useRecoilState(todoListState);
    //useSetRecoilState返回是一个修改值的函数,修改的时候会传入一个函数，接收老状态，返回新状态
    const setTodoList = useSetRecoilState(todoListState);
    //通过useRecoilValue可以获取状态的值,只是用来读取值的，不能修改状态
    const filteredTodoList = useRecoilValue(filteredTodoListState);
    //如果既想读取状态里的值，也想修改状态里的值就可以使用useRecoilState
    const [filter,setFilter] = useRecoilState(filterState);
    const toggleTodo = (id) => {
        setTodoList((oldTodoList) => {
            //映射老数组
            return oldTodoList.map(todo => {
                //遍历每个todo,如果此todo的ID和传入的ID相同，则覆盖completed,否则不变
                if (todo.id === id) {
                    return { ...todo, completed: !todo.completed };
                }
                return todo;
            });
        });
    }
    //调用增加一个todo的方法，传入输入的新的todo的文本
    const addTodo = (text) => {
        //调用setTodoList修改todoList数组
        setTodoList((oldTodoList) => [...oldTodoList,
        { id: oldTodoList.length + 1, text, completed: false }]);
        textRef.current.value = '';
    }
    return (
        <div>
            <input type="text" ref={textRef} />
            <button onClick={() => addTodo(textRef.current.value)}>添加</button>
            <div>
                Filter:
                <select value={filter} onChange={(event)=>setFilter(event.target.value)}>
                    <option value="SHOW_ALL">全部</option>
                    <option value="SHOW_COMPLETED">已完成</option>
                    <option value="SHOW_UNCOMPLETED">未完成</option>
                </select>
            </div>
            <ul>
                {
                    filteredTodoList.map(todo => (
                        <li key={todo.id}>
                            <input
                                type="checkbox"
                                checked={todo.completed}
                                onChange={() => toggleTodo(todo.id)} />
                            {todo.text}
                        </li>
                    ))
                }
            </ul>
        </div>
    )
}

export default RecoilApp;
/**
useRecoilValue,useRecoilState,useSetRecoilState
都是用来读取原子或派发状态的
useRecoilValue 返回的值
useSetRecoilState 返回是修改值的方法
useRecoilState 返回的是一个数组[值,修改值的方法]
 */